package de.cau.apo.utils;

import java.io.IOException;
import java.io.InputStream;

public class InputStreamParser {

    /**
     * Read the next integer number from the input stream.
     * @param is the input stream to read from
     * @return the read integer otherwise
     * @throws IOException when EOF char occurred and no integer was found
     */
    public static int readNextInt(InputStream is) throws IOException {
        int c = is.read();
        int negative = 1;
        while (c < 48 || c > 57) {
            if (c == -1) {
                throw new IOException("Received EOF and no integer found to parse.");
            }
            negative = c == '-' ? -1 : 1;
            c = is.read();
        }
        int number = 0;
        while (c >= 48 && c <= 57) {
            number = (number * 10) + (c - 48);
            c = is.read();
        }
        return negative * number;
    }
    
    /**
     * Read the next float number from the string.
     * @param is the input stream to read from
     * @return the read float otherwise
     * @throws IOException when EOF char occurred and no integer was found
     */
    public static float readNextFloat(InputStream is) throws IOException {
        int c = is.read();
        int negative = 1;
        while (c < 48 || c > 57) {
            if (c == -1) {
            	throw new IOException("Received EOF and no float found to parse.");
            }
            negative = c == '-' ? -1 : 1;
            c = is.read();
        }
        float number = 0;
        while (c >= 48 && c <= 57) {
            number = (number * 10) + (c - 48);
            c = is.read();
        }
        if (c == 46) {
        	c = is.read();
        	int floatPart = 0;
        	int numFloatNumbers = 0;
        	while (c >= 48 && c <= 57) {
        		floatPart = (floatPart * 10) + (c - 48);
        		numFloatNumbers++;
                c = is.read();
            }
        	number += (float) floatPart / (float) numFloatNumbers;
        }
        return negative * number;
    }
    
}
